import Layout from '@/layout'
import { doGet } from './utils'

export const initAsyncRoutes = () => {
  return new Promise((resolve, reject) => {
    doGet('/sys-menu/admin/list-all-menu', {}).then(res => {
      const asyncRoutes = initRoutes(res.data)
      resolve(asyncRoutes)
    }).catch(error => { reject(error) })
  })
}

const initRoutes = (sysMenus) => {
  let asyncRoutes = []
  // 获取到所有一级菜单
  let oneLevelMenuArr = sysMenus.filter((item) => {
    return item.menuLevel === 1
  })
  // 获取到所有二级菜单
  let twoLevelMenuArr = sysMenus.filter((item) => {
    return item.menuLevel === 2
  })
  // 获取到所有三级菜单
  let threeLevelMenuArr = sysMenus.filter((item) => {
    return item.menuLevel === 3
  })
  // 循环一级菜单
  oneLevelMenuArr.forEach((oneLevelMenu) => {
    const oneLevelRoute = encapsulationRoute(oneLevelMenu, 1)
    let oneMenuId = oneLevelMenu.id
    let oneLevelChildren = []
    // 循环二级菜单
    twoLevelMenuArr.forEach((twoLevelMenu) => {
      if (oneMenuId === twoLevelMenu.parentId) {
        let twoMenuId = twoLevelMenu.id
        let twoLevelChildren = []
        // 循环三级菜单
        threeLevelMenuArr.forEach((threeLevelMenu) => {
          if (twoMenuId === threeLevelMenu.parentId) {
            const threeLevelRoute = encapsulationRoute(
              threeLevelMenu,
              3
            )
            twoLevelChildren.push(threeLevelRoute)
          }
        })
        const twoLevelRoute = encapsulationRoute(twoLevelMenu, 2)
        twoLevelRoute.children = twoLevelChildren
        oneLevelChildren.push(twoLevelRoute)
      }
    })
    oneLevelRoute.children = oneLevelChildren
    asyncRoutes.push(oneLevelRoute)
  })
  asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
  return asyncRoutes
}

const encapsulationRoute = (sysMenu, menuLevel) => {
  let route = {
    component: menuLevel === 1 ? Layout : (resolve) => require([`@/views${sysMenu.component}`], resolve)
    
  }
  route.path = sysMenu.path
  route.name = sysMenu.name
  if (sysMenu.redirect !== null) {
    route.redirect = sysMenu.redirect
  }
  if (sysMenu.alwaysShow !== null) {
    route.alwaysShow = sysMenu.alwaysShow
  }
  if (sysMenu.hidden !== null) {
    route.hidden = sysMenu.hidden
  }
  let meta = {}
  meta.title = sysMenu.metaTitle
  if (sysMenu.metaIcon !== null) {
    meta.icon = sysMenu.metaIcon
  }
  if (sysMenu.metaRoles !== null) {
    meta.roles = sysMenu.metaRoles.split(',')
  }
  if (sysMenu.metaNoCache !== null) {
    meta.noCache = sysMenu.metaNoCache
  }
  if (sysMenu.metaAffix !== null) {
    meta.affix = sysMenu.metaAffix
  }
  if (sysMenu.metaBreadcrumb !== null) {
    meta.breadcrumb = sysMenu.metaBreadcrumb
  }
  route.meta = meta
  return route
}